<?php
require_once("database.php");

function participants_POST($id)
{
	$db = getDBConnection();
	
	$sql = "INSERT INTO participant (id) VALUES ('".$id."')";
	$result = mysqli_query($db, $sql);
	
	$uid = mysqli_insert_id($db);
	$arr = array("uid" => $uid);
	
	return $arr;
}

function participants_GET($id)
{
	$db = getDBConnection();
	
	$sql = "SELECT * FROM participant WHERE id = '".$id."' ORDER BY uid";
	$result = mysqli_query($db, $sql);
	$participant_data = array();
	
	$count = 0;
	if(($count = mysqli_num_rows($result)) > 0)
	{
		for($i = 0; $i < $count; $i++)
		{
			$row = mysqli_fetch_assoc($result);
			$participant_data[$i]["uid"] = $row["uid"];
			$participant_data[$i]["id"] = $id;
		}
	}else
	{
		printErrorCode(404);
	}
	
	return $participant_data;
}

function participant_GET($id, $uid)
{
	$db = getDBConnection();
	
	$sql = "SELECT * FROM participant WHERE id = '".$id."' AND uid = '".$uid."'";
	$result = mysqli_query($db, $sql);
	$participant_data = array();
	
	if(mysqli_num_rows($result) > 0)
	{
		$row = mysqli_fetch_assoc($result);
		$participant_data["uid"] = $uid;
		$participant_data["id"] = $id;
	}else
	{
		printErrorCode(404);
	}
	
	return $participant_data;
}

function participant_PUT($id, $uid)
{
	return 0;
}

function participant_DELETE($id, $uid)
{
	$db = getDBConnection();
	
	$sql = "SELECT uid FROM participant WHERE id = '".$id."' AND uid = '".$uid."'";
	$result = mysqli_query($db, $sql);
	if(mysqli_num_rows($result) == 0)
	{
		printErrorCode(404);
	}else
	{	
		$sql = "DELETE FROM participant WHERE id = '".$id."' AND uid = '".$uid."'";
		mysqli_query($db, $sql);
		
		$sql = "DELETE FROM answer WHERE id = '".$id."' AND uid = '".$uid."'";
		mysqli_query($db, $sql);
	}
	
	return 0;
}

function participants_answers_GET($id, $uid)
{
	$db = getDBConnection();
	
	$sql = "SELECT * FROM answer WHERE id = '".$id."' AND uid = '".$uid."'";
	$result = mysqli_query($db, $sql);
	$answer_data = array();
	
	$count = 0;
	if(($count = mysqli_num_rows($result)) > 0)
	{
		for($i = 0; $i < $count; $i++)
		{
			$row = mysqli_fetch_assoc($result);
			$answer_data[$i]["id"] = $id;
			$answer_data[$i]["qid"] = $row["qid"];
			$answer_data[$i]["uid"] = $uid;
			$answer_data[$i]["answer"] = $row["answer"];
			$answer_data[$i]["time"] = $row["time"];
		}
	}else
	{
		printErrorCode(404);
	}

	return $answer_data;
}

?>